package com.bestcem.xm.ticket.controller;

import cn.hutool.core.lang.ObjectId;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.domain.web.XmResultJson;
import com.bestcem.xm.common.core.enums.ReqErrorCodeEnum;
import com.bestcem.xm.component.security.context.SecurityContextHolder;
import com.bestcem.xm.ticket.controller.param.ticket.notify.setting.UpdateSettingParam;
import com.bestcem.xm.ticket.entity.mongo.NotifySetting;
import com.bestcem.xm.ticket.service.TicketNotifySettingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局工单通知配置的增删改查
 *
 * @author zq.ding <zq.ding@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/31 10:38
 */
@Slf4j
@RestController
@RequestMapping(value = "/ticket/notifysettings", produces = MediaType.APPLICATION_JSON_VALUE)
public class TicketNotifySettingsController {

    @Resource
    private TicketNotifySettingService ticketNotifySettingService;

    @Resource
    private HttpServletRequest request;

    /**
     * 获取全局工单通知配置
     *
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/20 17:50
     */
    @GetMapping(value = "/")
    public XmResultJson<NotifySetting> getGlobalTicketSetting() {
        String orgId = SecurityContextHolder.getOrgId();
        if (!ObjectId.isValid(orgId)) {
            return XmResultJson.fail(ReqErrorCodeEnum.PARAM_FORMAT, "组织id错误");
        }
        ServiceResult<NotifySetting> result = ticketNotifySettingService.getEntityByOrgId(orgId);
        if (!result.isSuccess()) {
            return XmResultJson.fail(result.getErrorData(), result.getMsg());
        }

        return XmResultJson.success(result.getData());
    }


    /**
     * 更新全局工单通知配置
     *
     * @author zq.ding <zq.ding@idiaoyan.com>
     * @date 2021/8/20 18:48
     */
    @PutMapping(value = "/")
    public XmResultJson<String> updateGlobalTicketSetting(@RequestBody UpdateSettingParam param) {
        String orgId = SecurityContextHolder.getOrgId();
        param.setId(null);
        param.setOrgId(orgId);
        ServiceResult<String> result = ticketNotifySettingService.updateSetting(param);
        if (result.isSuccess()) {
            return XmResultJson.success(result.getData());
        }

        return XmResultJson.fail(result.getErrorData(), result.getMsg());
    }
}
